import React, { useState } from 'react';
import SHA512 from 'crypto-js/sha512';
import styles from './login.module.css';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const Login = () => {
    const navigate = useNavigate();
    const [loginData, setLoginData] = useState({
        username: '',
        password: ''
    });
    const [errorMessage, setErrorMessage] = useState('');
    const [successMessage, setSuccessMessage] = useState('');

    const handleChange = (e) => {
        const { name, value } = e.target;
        setLoginData({
            ...loginData,
            [name]: value
        });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        // 清空之前的消息
        setErrorMessage('');
        setSuccessMessage('');
        
        // 验证表单
        if (!loginData.username.trim()) {
            setErrorMessage('请输入用户名');
            return;
        }
        
        if (!loginData.password) {
            setErrorMessage('请输入密码');
            return;
        }
        
        try {
            // 这里添加登录逻辑 - 使用与注册相同的哈希方法
            const hashedPassword = SHA512(loginData.password).toString();
            const res = await axios.post("http://localhost:3000/login", {
                username: loginData.username,
                password: hashedPassword
            });
            
            if (res.data.code === 200) {
                setSuccessMessage('登录成功！正在跳转...');
                // 延迟2秒后跳转
                if (res.data.userId) {
                    localStorage.setItem('userId', res.data.userId);
                }
                
                setTimeout(() => {
                    navigate("/register");  
                }, 2000);
            } else {
                setErrorMessage(res.data.message || '登录失败，请检查用户名和密码');
            }
        } catch (error) {
            console.error('登录错误:', error);
            setErrorMessage('网络错误，请稍后重试');
        }
    };

    const WX = async () => {
        axios.defaults.baseURL = "";
        await axios
            .get("/api", {
                params: {
                    act: "login",
                    appid: "3521",
                    appkey: "a010aaf9582fe1587b08b283a47ca14b",
                    type: "wx",
                    redirect_uri: "http://127.0.0.1:5173/homepage",
                },
            })
            .then((res) => {
                sessionStorage.setItem("longtermToken", "hhhhnxsm");
                console.log(res.data.url);
                
                // 直接使用微信返回的URL进行跳转
                window.open(res.data.url, "_self");
                
            });
    };

    const QQ = async () => {
        axios.defaults.baseURL = "";
        await axios
            .get("/api", {
                params: {
                    act: "login",
                    appid: "3521",
                    appkey: "a010aaf9582fe1587b08b283a47ca14b",
                    type: "qq",
                    redirect_uri: "http://127.0.0.1:5173/homepage",
                },
            })
            .then((res) => {
                sessionStorage.setItem("longtermToken", "hhhhnxsm");
                window.open(res.data.url, "_self");
            });
    };

    return (
        <div className={styles.loginContainer}>
            <div className={styles.loginBox}>
                <h2 className={styles.loginTitle}>用户登录</h2>
                
                {successMessage && (
                    <div className={styles.successMessage}>{successMessage}</div>
                )}
                
                {errorMessage && (
                    <div className={styles.errorMessage}>{errorMessage}</div>
                )}

                <form className={styles.loginForm} onSubmit={handleSubmit}>
                    <div className={styles.formGroup}>
                        <input
                            type="text"
                            name="username"
                            placeholder="用户名/手机号"
                            value={loginData.username}
                            onChange={handleChange}
                            required
                        />
                    </div>

                    <div className={styles.formGroup}>
                        <input
                            type="password"
                            name="password"
                            placeholder="请输入密码"
                            value={loginData.password}
                            onChange={handleChange}
                            required
                        />
                    </div>

                    <div className={styles.formOptions}>
                        <div className={styles.rememberMe}>
                            <div>
                                <input type="checkbox" /> 记住我
                            </div>
                            <div className={styles.face} onClick={()=>{navigate("/faceLogin")}}>人脸登录</div>
                        </div>
                        <a href="#" className={styles.forgotPassword}>忘记密码?</a>
                    </div>

                    <button type="submit" className={styles.loginButton}>登录</button>
                </form>

                <div className={styles.loginDivider}>
                    <span>或使用第三方账号登录</span>
                </div>

                <div className={styles.thirdPartyLogin}>
                    <button
                        className={styles.wechatLogin}
                        onClick={WX}
                    >
                        <i className={styles.wechatIcon}></i>
                        微信登录
                    </button>

                    <button
                        className={styles.qqLogin}
                        onClick={QQ}
                    >
                        <i className={styles.qqIcon}></i>
                        QQ登录
                    </button>
                </div>

                <div className={styles.registerLink}>
                    还没有账号? <a href="/register">立即注册</a>
                </div>
            </div>
        </div>
    );
};

export default Login;
